package com.example.calllogplugin;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;

public class CallLogPlugin extends UniModule {

    @UniJSMethod(uiThread = true)
    public void getCallLogs(UniJSCallback callback) {
        Context context = getContext();
        if (context == null) {
            callback.invoke(createError("Context is null"));
            return;
        }

        ContentResolver cr = context.getContentResolver();

        Cursor cursor = null;
        try {
            cursor = cr.query(CallLog.Calls.CONTENT_URI,
                    null, null, null, CallLog.Calls.DATE + " DESC");
            if (cursor == null) {
                callback.invoke(createError("Failed to query call logs"));
                return;
            }

            JSONArray callLogsArray = new JSONArray();

            while (cursor.moveToNext()) {
                JSONObject callLog = new JSONObject();
                String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));

                callLog.put("number", number);
                callLog.put("type", type);
                callLog.put("date", date);
                callLog.put("duration", duration);

                callLogsArray.put(callLog);
            }
            callback.invoke(callLogsArray);
        } catch (SecurityException e) {
            callback.invoke(createError("Permission denied: " + e.getMessage()));
        } catch (JSONException e) {
            callback.invoke(createError("JSON error: " + e.getMessage()));
        } finally {
            if (cursor != null) cursor.close();
        }
    }

    private JSONObject createError(String msg) {
        JSONObject err = new JSONObject();
        try {
            err.put("error", msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return err;
    }
}
